package com.example.xxcjgl.viewmodel

import androidx.compose.runtime.State
import androidx.compose.runtime.mutableStateOf
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.example.xxcjgl.data.api.RetrofitClient
import com.example.xxcjgl.data.models.LoginRequest
import com.example.xxcjgl.data.models.Resource
import com.example.xxcjgl.data.models.User
import com.example.xxcjgl.data.repository.UserRepository
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.launch
import javax.inject.Inject

// AuthViewModel.kt
@HiltViewModel
class AuthViewModel @Inject constructor(
    private val userRepository: UserRepository
) : ViewModel() {

    private val _loginState = MutableStateFlow<Resource<User>>(Resource.Initial)
    val loginState: StateFlow<Resource<User>> = _loginState

    // 使用 mutableStateOf 创建真正的 Compose State
    private val _captcha = mutableStateOf(generateCaptcha())

    // 暴露为只读的 State
    val captcha: State<String> get() = _captcha

    fun login(username: String, password: String, captcha: String) {
        viewModelScope.launch {
            _loginState.value = Resource.Loading()
            val result = userRepository.login(username, password, captcha)
            _loginState.value = result
        }
    }

    fun refreshCaptcha() {
        _captcha.value = generateCaptcha()
    }

    private fun generateCaptcha(): String {
        val chars = "ABCDEFGHJKLMNPQRSTUVWXYZ23456789"
        return (1..4).map { chars.random() }.joinToString("")
    }

    private fun saveLoginState(username: String, user: User) {
        // 使用SharedPreferences保存登录状态
    }
}

